<?php


namespace EchoPHP\Rabbitmq;


use EchoPHP\Facades\Log;

class QueueConnector {

    /**
     * rabbitmq连接实例
     * @var null|\AMQPConnection
     */
    protected $connection;

    /**
     * 连接rabbitmq服务器
     * @param $name
     * @param $config
     * @return \AMQPConnection
     */
    public function connect($name, $config) {
        $credentials = [
            'host' => $config['host'],
            'port' => $config['port'],
            'vhost' => $config['vhost'],
            'login' => $config['login'],
            'password' => $config['password'],
        ];
        $persistent = isset($config['persistent']) && $config['persistent'] ? true : false;
        return $this->establishConnection($name, $persistent, $credentials);
    }

    /**
     * 建立连接
     * @param $name 连接标识
     * @param bool $persistent 是否长连接
     * @param array $credentials 连接配置
     * @return bool
     */
    protected function establishConnection($name, bool $persistent, array $credentials) {
        $connection = new \AMQPConnection($credentials);

        $reconnectTimes = 0;
        while ($reconnectTimes < 5) {
            try {
                $connection->{($persistent ? 'pconnect' : 'connect')}();
                return $connection;
            } catch (\Exception $e) {
                Log::error('rabbitmq服务器连接失败,name:[' . $name . ']' . ',reason:[' . $e->getMessage() . ']');
            }
            $reconnectTimes++;
        }
        throw new \RuntimeException('RabbitMq 服务无法连接');
    }

}